<template>
  <div class="userPortrait">
    <el-card shadow="hover">
      <!-- 数据总览 -->
      <div class="dataScreeningBox">
        <h4>数据总览</h4>
        <el-card class="cardItem">
          <h3>用户总数</h3>
          <p>{{ userTotal }}</p>
          <el-divider></el-divider>
          <span>{{ time }}</span>
        </el-card>
      </div>
      <!-- 搜索 -->
      <div class="searchBox">
        <div class="txt">请选择渠道</div>
        <el-select v-model="channelValue" placeholder="请选择渠道">
          <el-option
            v-for="item in channelOptions"
            :key="item.cn_name"
            :label="item.cn_name"
            :value="item.en_name"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-model="userPortraitTimeVal"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="userPortraitPickerOptions"
          value-format="yyyy-MM-dd"
          @change="userPortraitFocus"
        >
        </el-date-picker>
        <el-button class="btn" icon="el-icon-search" @click="userPortraitBtn"
          >查询搜索</el-button
        >
        <el-button class="btn" icon="el-icon-download" @click="exportExcel"
          >导出Excel</el-button
        >
      </div>

      <div class="chartBox">
        <div id="myChartA" :style="{ width: '100%', height: '500px' }"></div>
        <div id="myChartB" :style="{ width: '100%', height: '500px' }"></div>
      </div>

      <div class="mapBox">
        <div id="myChartC" :style="{ width: '100%', height: '500px' }"></div>
        <div class="mapList">
          <el-radio-group v-model="type">
            <el-radio-button label="1">省份</el-radio-button>
            <el-radio-button label="2">城市</el-radio-button>
          </el-radio-group>
          <br />
          <br />
          <el-table
            :data="type == 1 ? area : city"
            height="450"
            style="width: 100%"
            :header-cell-style="header"
          >
            <el-table-column prop="name" label="名称" width="180">
            </el-table-column>
            <el-table-column
              prop="value"
              label="人数"
              column-key="value"
              width="180"
              sortable
            >
            </el-table-column>
          </el-table>
          <!-- <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="省" name="first">
              <div class="province">
                <p v-for="(item, index) in area" :key="index">
                  <span>{{ item.name }}</span
                  ><span>{{ item.value }}</span>
                </p>
              </div>
            </el-tab-pane>
            <el-tab-pane label="市" name="second">
              <div class="city">
                <p v-for="(item, index) in city" :key="index">
                  <span>{{ item.name }}</span
                  ><span>{{ item.value }}</span>
                </p>
              </div>
            </el-tab-pane>
          </el-tabs> -->
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import "@/assets/map/js/china"; // 引入中国地图数据
import { userPortrait, portraitChart } from "@/api/UserManagement";
import { channellist } from "@/api/DataAnalysis";

export default {
  inject: ["reload"],
  data() {
    return {
      userTotal: "",
      time: "",
      //渠道
      channelOptions: [],
      channelValue: "", //渠道下拉框
      //用户画像日期
      userPortraitPickerOptions: {
        disabledDate(platformValue) {
          return platformValue.getTime() > Date.now() - 8.64e6;
        },
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      userPortraitTimeValStartDate: "",
      userPortraitTimeValEndDate: "",
      userPortraitTimeVal: "", //用户画像时间

      activeName: "first",
      area: [],
      city: [],
      type: "1",
    };
  },
  methods: {
    header() {
      return "text-align: center;background:#eef1f6;";
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    //用户画像时间
    userPortraitFocus(time) {
      if (!this.userPortraitTimeVal) {
        this.userPortraitTimeVal = [];
      }
      this.userPortraitTimeValStartDate = this.userPortraitTimeVal[0];
      this.userPortraitTimeValEndDate = this.userPortraitTimeVal[1];
    },
    // 搜索
    userPortraitBtn() {
      this.pin();
    },
    //性别分析饼图
    async pin() {
      const res = await portraitChart({
        channelId: this.channelValue,
        startTime: this.userPortraitTimeValStartDate,
        endTime: this.userPortraitTimeValEndDate,
      });
      this.city = res.data.city;
      this.area = res.data.area;
      //字符串value转换数字value
      this.city.forEach((item) => {
        item.value = parseInt(item.value);
      });
      this.area.forEach((item) => {
        item.value = parseInt(item.value);
      });
      // 基于准备好的dom，初始化echarts实例
      let myChartA = this.$echarts.init(document.getElementById("myChartA"));
      // 绘制图表
      myChartA.setOption({
        color: ["#59b2ef", "#2ac8ca", "#ffba81"],
        title: {
          text: "性别分布",
          subtext: "",
          left: "center",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: ["女", "男", "其他"],
        },
        series: [
          {
            name: "性别分布",
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: res.data.gender,
            // [
            //   { value: 335, name: "女" },
            //   { value: 234, name: "其他" },
            //   { value: 310, name: "男" },
            // ]
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });

      // 基于准备好的dom，初始化echarts实例
      let myChartB = this.$echarts.init(document.getElementById("myChartB"));
      // 绘制图表
      myChartB.setOption({
        color: [
          "#59b2ef",
          "#2ac8ca",
          "#ffba81",
          "#d97b81",
          "#b7a3df",
          "#8e99b4",
        ],
        title: {
          text: "年龄段统计",
          subtext: "",
          left: "center",
        },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          left: "left",
          data: ["0-17岁", "18-24岁", "25-32岁", "33-40岁", "41岁以上", "未知"],
        },
        series: [
          {
            name: "年龄段统计",
            type: "pie",
            radius: "55%",
            center: ["50%", "60%"],
            data: res.data.age,
            //  [
            //   { value: 335, name: "0-17岁" },
            //   { value: 310, name: "18-24岁" },
            //   { value: 234, name: "25-32岁" },
            //   { value: 234, name: "33-40岁" },
            //   { value: 234, name: "41岁" },
            //   { value: 234, name: "未知" },
            // ]
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      });

      // 基于准备好的dom，初始化echarts实例
      let myChartC = this.$echarts.init(document.getElementById("myChartC"));
      // 绘制图表
      myChartC.setOption({
        title: {
          text: "",
          subtext: "",
          left: "center",
        },
        visualMap: {
          show: true,
          min: 0, // 指定 visualMapContinuous 组件的允许的最小值。'min' 必须用户指定。[visualMap.min, visualMax.max] 形成了视觉映射的『定义域』。
          max: 1000, // 指定 visualMapContinuous 组件的允许的最大值
          text: ["High", "Low"], // 两端的文本，如 ['High', 'Low'] 如例子：http://www.echartsjs.com/gallery/editor.html?c=doc-example/map-visualMap-continuous-text&edit=1&reset=1
          textStyle: {
            color: "#6F7082",
          },
          realtime: false, // 拖拽时，是否实时更新。
          calculable: false, // 是否显示拖拽用的手柄（手柄能拖拽调整选中范围）。
          hoverLink: true, // 打开 hoverLink 功能时，鼠标悬浮到 visualMap 组件上时，鼠标位置对应的数值 在 图表中对应的图形元素，会高亮。
          //   inRange: {
          //     // inRange (object)定义 在选中范围中 的视觉元素。（用户可以和 visualMap 组件交互，用鼠标或触摸选择范围）1、symbol: 图元的图形类别。2、symbolSize: 图元的大小。3、color: 图元的颜色。4、colorAlpha: 图元的颜色的透明度。5、opacity: 图元以及其附属物（如文字标签）的透明度。6、
          //     color: ["lightskyblue", "yellow", "orangered"],
          //   },
          pieces: [
            //根据数据大小，各省显示不同颜色
            {
              gte: 100,
              label: ">= 1000",
              color: "#1690ff",
            },
            {
              gte: 500,
              lt: 999,
              label: "500 - 999",
              color: "#3aa4f9",
            },
            {
              gte: 100,
              lt: 499,
              label: "100 - 499",
              color: "#50b0f5",
            },
            {
              gte: 10,
              lt: 99,
              label: "10 - 99",
              color: "#72c2ef",
            },
            {
              lt: 10,
              label: "<10",
              color: "#87ceeb",
            },
          ],
        },
        geo: {
          map: "china",
          roam: false, // 是否开启鼠标缩放和平移漫游。默认不开启。如果只想要开启缩放或者平移，可以设置成 'scale' 或者 'move'。设置成 true 为都开启
          aspectScale: 0.75,
          zoom: 1.2,
          label: {
            normal: {
              show: false,
              textStyle: {
                color: "#fff",
              },
            },
            emphasis: {
              // 对应的鼠标悬浮效果
              show: true,
              textStyle: {
                color: "#000",
              },
            },
          },
          itemStyle: {
            normal: {
              //未选中状态
              areaColor: "#eeeeee", //背景颜色
              borderColor: "#7c7c7c",
            },
            emphasis: {
              borderWidth: 0.5,
              borderColor: "#7c7c7c",
              areaColor: "#ffdf33",
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
        tooltip: {
          trigger: "item",
          formatter: (params) => {
            let value = 0;
            if (params.value) {
              value = params.value;
            }
            return params.name + ":" + value;
          },
        },
        series: [
          {
            type: "map",
            roam: true,
            coordinateSystem: "geo",
            geoIndex: 0,
            aspectScale: 0.75,
            zoom: 1.2,
            label: {
              normal: {
                formatter: "{b}",
                position: "right",
                show: false,
              },
              emphasis: {
                show: true,
              },
            },
            itemStyle: {
              normal: {
                color: "#FFFD00",
              },
            },
            data: res.data.area,
            // 自定义名称映射
            // [
            //   // value可以对应的相应的颜色区域值
            //   {
            //     name: "北京",
            //     value: 1200,
            //   },
            //   {
            //     name: "天津",
            //     value: 120,
            //   },
            //   {
            //     name: "上海",
            //     value: 80,
            //   },
            //   {
            //     name: "重庆",
            //     value: 100,
            //   },
            //   {
            //     name: "河北",
            //     value: 100,
            //   },
            //   {
            //     name: "河南",
            //     value: 100,
            //   },
            //   {
            //     name: "云南",
            //     value: 40,
            //   },
            //   {
            //     name: "辽宁",
            //     value: 120,
            //   },
            //   {
            //     name: "黑龙江",
            //     value: 100,
            //   },
            //   {
            //     name: "湖南",
            //     value: 80,
            //   },
            //   {
            //     name: "安徽",
            //     value: 80,
            //   },
            //   {
            //     name: "山东",
            //     value: 100,
            //   },
            //   {
            //     name: "新疆",
            //     value: 400,
            //   },
            //   {
            //     name: "江苏",
            //     value: 80,
            //   },
            //   {
            //     name: "浙江",
            //     value: 60,
            //   },
            //   {
            //     name: "江西",
            //     value: 80,
            //   },
            //   {
            //     name: "湖北",
            //     value: 100,
            //   },
            //   {
            //     name: "广西",
            //     value: 40,
            //   },
            //   {
            //     name: "甘肃",
            //     value: 120,
            //   },
            //   {
            //     name: "山西",
            //     value: 120,
            //   },
            //   {
            //     name: "内蒙古",
            //     value: 140,
            //   },
            //   {
            //     name: "陕西",
            //     value: 120,
            //   },
            //   {
            //     name: "吉林",
            //     value: 120,
            //   },
            //   {
            //     name: "福建",
            //     value: 60,
            //   },
            //   {
            //     name: "贵州",
            //     value: 80,
            //   },
            //   {
            //     name: "广东",
            //     value: 40,
            //   },
            //   {
            //     name: "青海",
            //     value: 100,
            //   },
            //   {
            //     name: "西藏",
            //     value: 40,
            //   },
            //   {
            //     name: "四川",
            //     value: 900,
            //   },
            //   {
            //     name: "宁夏",
            //     value: 140,
            //   },
            //   {
            //     name: "海南",
            //     value: 20,
            //   },
            //   {
            //     name: "台湾",
            //     value: 40,
            //   },
            //   {
            //     name: "香港",
            //     value: 200,
            //   },
            //   {
            //     name: "澳门",
            //     value: 20,
            //   },
            // ],
          },
        ],
      });
    },
    //数据总览
    getUserPortrait() {
      userPortrait().then((res) => {
        if (res.code == 0) {
          this.userTotal = res.data.total;
          this.time = res.data.time;
        }
      });
    },
    //渠道
    getChannellist() {
      channellist().then((res) => {
        this.channelOptions = res.data;
      });
    },
    //导出
    exportExcel() {
      require.ensure([], async () => {
        const res = await portraitChart({
          channelId: this.channelValue,
          startTime: this.userPortraitTimeValStartDate,
          endTime: this.userPortraitTimeValEndDate,
        });
        const { export_json_to_excel } = require("@/excel/Export2Excel"); //注意这个Export2Excel路径
        const tHeader = ["用户画像", ""]; // 上面设置Excel的表格第一行的标题
        let data = [];
        data.push(["性别", "人数"]);
        res.data.gender.forEach((item) => {
          data.push([item.name, item.value]);
        });
        data.push(["年龄段", "人数"]);
        res.data.age.forEach((item) => {
          data.push([item.name, item.value]);
        });
        export_json_to_excel(tHeader, data, "用户画像"); //最后一个是表名字
      });
    },
  },
  created() {
    this.getUserPortrait();
    this.getChannellist();
  },
  mounted() {
    this.pin();
  },
};
</script>

<style lang="less" scoped>
.userPortrait {
  margin: 30px;
  height: 100%;
  .dataScreeningBox {
    .cardItem {
      width: 260px;
      h3 {
        margin: 0px;
      }
      p {
        font-weight: bold;
        font-size: 20px;
      }
    }
  }
  .searchBox {
    .txt {
      line-height: 40px;
      color: #333;
      margin-right: 10px;
    }
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    .el-select {
      margin-right: 20px;
    }
  }
  .chartBox {
    display: flex;
    margin-top: 80px;
  }
  .mapBox {
    display: flex;
    margin-top: 60px;
    .mapList {
      width: 50%;
      .province,
      .city {
        p {
          span {
            margin-right: 60px;
          }
        }
      }
    }
  }
}
</style>